package com.useeinfo.oa.modules.inspection.entity;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.extend.entity.SuperClassEntity;
import com.useeinfo.framework.sugar.tools.CommonSugar;
import com.useeinfo.framework.sugar.tools.DateTimeUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.base.entity.Organization;
import com.useeinfo.oa.modules.base.entity.Position;
import com.useeinfo.oa.modules.base.entity.Resource;
import com.useeinfo.oa.modules.inspection.enums.InsApplyTypeEnum;
import com.useeinfo.oa.modules.inspection.enums.InsOrderAssignTypeEnum;
import com.useeinfo.oa.modules.inspection.enums.InsOrderStatusEnum;
import com.useeinfo.oa.modules.maintaining.entity.ApplyOrder;
import com.useeinfo.oa.modules.maintaining.entity.AuditOrder;
import com.useeinfo.oa.modules.maintaining.enums.ApplyTypeEnum;
import com.useeinfo.oa.modules.maintaining.enums.OrderStatusEnum;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.format.annotation.DateTimeFormat;

import javax.persistence.*;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Auther: xudong.sun
 * @Date: 2018/12/28 17:16
 * @Description:PlannerInstpection 巡检工单
 */
@Entity
@Table(name = "inspection_order")
public class InspectionOrder extends SuperClassEntity<InspectionOrder> {

    /**
     * 单号
     */
    private String orderCode;

    /**
     * 名称
     */
    private String orderName;

    /**
     * 工单类型 false 周期性  true 一次性
     */
    @Column(columnDefinition = "bit default 0")
    private boolean orderType;

    /**
     * 提醒时间
     */
    private int remindTime = 2;

    /**
     * 完成百分比
     */
    @Column(columnDefinition = "int default 0")
    private int percent;
    /**
     * 所属部门
     */
    @ManyToOne
    @JoinColumn(name = "belong_organization_id")
    private Organization belongOganization;

    /**
     * 是否异常 true 为异常
     */
    @Column(columnDefinition = "bit default 0")
    private boolean abnormal;

    /**
     * 是否处于审核中——用于判断不可重复提交审核
     */
    @Column(columnDefinition = "bit default 0")
    private boolean auditing;

    /**
     * 提醒的确切时间点
     */
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date remindDateTime;
    /**
     * 是否延期
     */
    private boolean delay = false;

    /**
     * 最新申请延期日期
     */
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date delayTime;
    /**
     * 最新延期申请人
     */
    @ManyToOne
    @JoinColumn(name = "delay_user_id")
    private SystemUser delayUser;

    /**
     * 是否取消申请
     */
    private boolean cancel = false;

    /**
     * 最新申请取消日期
     */
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date cancelDate;
    /**
     * 最新取消申请人
     */
    @ManyToOne
    @JoinColumn(name = "cancel_user_id")
    private SystemUser cancelUser;

    /**
     * 工作要求
     */
    private String required;
    /**
     * 标准工分
     */
    private Long points;
    /**
     * 紧急程度
     */
    private String degree;
    /**
     * 工单类型
     */
    private String type;
    /**
     * 安全指导书
     */
    @Column(columnDefinition = "bit default 0")
    private boolean safeInstruction;
    /**
     * 安全指导书pdf
     */
    @ManyToOne
    @JoinColumn(name = "resource_id")
    private Resource resource;
    /**
     * 所属企业
     */
    @ManyToOne
    @JoinColumn(name = "enterprise_id")
    private Enterprise enterprise;
    /**
     * 所属计划
     */
    @ManyToOne
    @JoinColumn(name = "planner_inspection_id")
    private PlannerInspection plannerInspection;

    /**
     * 工单状态
     */
    @Enumerated(value = EnumType.STRING)
    private InsOrderStatusEnum orderStatusEnum = InsOrderStatusEnum.WAIT_TAKING;
    /**
     * 是否接单
     */
    private boolean receive = false;

    /**
     * 接单人
     */
    @ManyToOne
    @JoinColumn(name = "receive_user_id")
    private SystemUser receiveUser;
    /**
     * 接单时间
     */
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date receiveDate;

    /**
     * 开始时间
     */
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date startDateTime;

    /**
     * 结束时间
     */
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date endDateTime;


    /**
     * 每次新建工单时与结束时间一直
     * 申请延期日期——真实时间（延期审核通过时设置该时间）
     * 用于比较是否逾期
     */
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date delayRealTime;


    /**
     * 是否指派
     */
    @Column(columnDefinition = "bit default 0")
    private boolean assign = false;

    /**
     * 是否到场
     */
    @Column(columnDefinition = "bit default 0")
    private boolean presence = false;

    /**
     * 到场时间
     */
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date presenceTime;
    /**
     * 到场人
     */
    @ManyToOne
    @JoinColumn(name = "presence_user_id")
    private SystemUser presenceUser;


    /**
     * 是否完成
     */
    @Column(columnDefinition = "bit default 0")
    private boolean complete = false;
    /**
     * 实际完成时间
     */
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date finishTime;
    /**
     * 完成人
     */
    @ManyToOne
    @JoinColumn(name = "complete_user_id")
    private SystemUser completeUser;

    /**
     * 指派人
     */
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "inspection_order_2_users", joinColumns = {
            @JoinColumn(name = "inspection_order_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")})
    private Set<SystemUser> assignUsers = new HashSet<>();


    /**
     * 参与人
     */
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "inspection_join_2_users", joinColumns = {
            @JoinColumn(name = "inspection_order_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")})
    private Set<SystemUser> joinUsers = new HashSet<>();


    /**
     * 指派岗位
     */
    @ManyToMany
    @JoinTable(name = "inspection_order_2_position", joinColumns = {
            @JoinColumn(name = "inspection_order_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "position_id", referencedColumnName = "id")})
    private Set<Position> assignPositions = new HashSet<>();

    /**
     * 指派类型
     */
    @Enumerated(value = EnumType.STRING)
    @Column(name = "order_assign_type")
    private InsOrderAssignTypeEnum orderAssignTypeEnum;

    /**
     * 创建人
     */
    @ManyToOne
    @JoinColumn(name = "create_user_id")
    private SystemUser createUser;


    /**
     * 到场后的经度
     */
    @Column(precision = 12, scale = 6)
    private BigDecimal longitude;

    /**
     * 到场后的纬度
     */
    @Column(precision = 12, scale = 6)
    private BigDecimal latitude;

    /**
     * 完成描述
     */
    private String completeRemark;

    /**
     * 未完成理由
     */
    private String unfinishReason;

    /**
     * 工单评分
     */
    @Column(columnDefinition = "int default 0")
    private int score;

    /******审批信息start——以快照形式********/
    /**
     * 完成——审批流快照
     */
    private String completeFlow;
    /**
     * 完成——审批流ID
     */
    private Long auditCompleteID;

    /**
     * 延期——审批流快照
     */
    private String delayFlow;
    /**
     * 延期——审批流ID
     */
    private Long delayFlowID;

    /**
     * 取消——审批流快照
     */
    private String cancelFlow;
    /**
     * 取消——审批流ID
     */
    private Long cancelFlowID;
    /***
     * 审核等级
     */
    @Column(columnDefinition = "int default 0")
    private int level = 0;
    /**
     * 是否初级审核
     */
    @Column(columnDefinition = "bit default 0")
    private boolean auditFirst;
    /**
     * 是否终极审核
     */
    @Column(columnDefinition = "bit default 0")
    private boolean auditLast;
    /***
     * 当前审批节点部门
     */
    @ManyToOne
    @JoinColumn(name = "organization_id")
    private Organization organization;
    /***
     * 当前审批节点岗位
     */
    @ManyToOne
    @JoinColumn(name = "position_id")
    private Position position;
    /***
     * 当前审批节点人员
     */
    @ManyToOne
    @JoinColumn(name = "auditSystemUser_id")
    private SystemUser auditSystemUser;

    /**
     * 关联申请记录
     */
    @OneToMany(mappedBy = "inspectionOrder", fetch = FetchType.LAZY)
    private Set<InsApplyOrder> insApplyOrders = new HashSet<>();
    /***
     * 当前审批管理申请记录
     */
    @ManyToOne
    @JoinColumn(name = "ins_apply_order_id")
    private InsApplyOrder insApplyOrder;
    /**
     * 关联审批纪录
     */
    @OneToMany(mappedBy = "inspectionOrder", fetch = FetchType.LAZY)
    private Set<InsAuditOrder> insAuditOrders = new HashSet<>();
    /**
     * 流水号(用来关联临时FacilityInspection表数据用的 其他地方不需要该字段)
     */
    private String serial;

    /**
     * 预计工时
     */
    private long expectWorkingHours;

    /**
     * 总工时
     */
    private long totalWorkingHours;

    /**
     * 我的工时
     */
    private long workingHours;

    /**
     * 终审备注
     */
    private String lastRemark;

    /**
     * app临时保存工时计算的标记
     */
    @Column(columnDefinition = "bit default 0")
    private boolean mark;

    /**
     * 是否缓存过此工单
     * @return
     */
    private boolean cache=false;


    public String getOrderCode() {
        return orderCode;
    }

    public void setOrderCode(String orderCode) {
        this.orderCode = orderCode;
    }

    public String getOrderName() {
        return orderName;
    }

    public void setOrderName(String orderName) {
        this.orderName = orderName;
    }

    public boolean isOrderType() {
        return orderType;
    }

    public void setOrderType(boolean orderType) {
        this.orderType = orderType;
    }

    public int getRemindTime() {
        return remindTime;
    }

    public void setRemindTime(int remindTime) {
        this.remindTime = remindTime;
    }

    public int getPercent() {
        return percent;
    }

    public void setPercent(int percent) {
        this.percent = percent;
    }

    public Organization getBelongOganization() {
        return belongOganization;
    }

    public void setBelongOganization(Organization belongOganization) {
        this.belongOganization = belongOganization;
    }

    public boolean isAbnormal() {
        return abnormal;
    }

    public void setAbnormal(boolean abnormal) {
        this.abnormal = abnormal;
    }

    public boolean isAuditing() {
        return auditing;
    }

    public void setAuditing(boolean auditing) {
        this.auditing = auditing;
    }

    public Date getRemindDateTime() {
        return remindDateTime;
    }

    public void setRemindDateTime(Date remindDateTime) {
        this.remindDateTime = remindDateTime;
    }

    public Boolean getDelay() {
        return delay;
    }

    public void setDelay(Boolean delay) {
        this.delay = delay;
    }

    public Date getDelayTime() {
        return delayTime;
    }

    public void setDelayTime(Date delayTime) {
        this.delayTime = delayTime;
    }

    public SystemUser getDelayUser() {
        return delayUser;
    }

    public void setDelayUser(SystemUser delayUser) {
        this.delayUser = delayUser;
    }

    public Boolean getCancel() {
        return cancel;
    }

    public void setCancel(Boolean cancel) {
        this.cancel = cancel;
    }

    public Date getCancelDate() {
        return cancelDate;
    }

    public void setCancelDate(Date cancelDate) {
        this.cancelDate = cancelDate;
    }

    public SystemUser getCancelUser() {
        return cancelUser;
    }

    public void setCancelUser(SystemUser cancelUser) {
        this.cancelUser = cancelUser;
    }

    public String getRequired() {
        return required;
    }

    public void setRequired(String required) {
        this.required = required;
    }

    public Long getPoints() {
        return points;
    }

    public void setPoints(Long points) {
        this.points = points;
    }

    public String getDegree() {
        return degree;
    }

    public void setDegree(String degree) {
        this.degree = degree;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public boolean isSafeInstruction() {
        return safeInstruction;
    }

    public void setSafeInstruction(boolean safeInstruction) {
        this.safeInstruction = safeInstruction;
    }

    public Resource getResource() {
        return resource;
    }

    public void setResource(Resource resource) {
        this.resource = resource;
    }

    public Enterprise getEnterprise() {
        return enterprise;
    }

    public void setEnterprise(Enterprise enterprise) {
        this.enterprise = enterprise;
    }

    public PlannerInspection getPlannerInspection() {
        return plannerInspection;
    }

    public void setPlannerInspection(PlannerInspection plannerInspection) {
        this.plannerInspection = plannerInspection;
    }

    public InsOrderStatusEnum getOrderStatusEnum() {
        return orderStatusEnum;
    }

    public void setOrderStatusEnum(InsOrderStatusEnum orderStatusEnum) {
        this.orderStatusEnum = orderStatusEnum;
    }

    public boolean isReceive() {
        return receive;
    }

    public void setReceive(boolean receive) {
        this.receive = receive;
    }

    public SystemUser getReceiveUser() {
        return receiveUser;
    }

    public void setReceiveUser(SystemUser receiveUser) {
        this.receiveUser = receiveUser;
    }

    public Date getReceiveDate() {
        return receiveDate;
    }

    public void setReceiveDate(Date receiveDate) {
        this.receiveDate = receiveDate;
    }

    public Date getStartDateTime() {
        return startDateTime;
    }

    public void setStartDateTime(Date startDateTime) {
        this.startDateTime = startDateTime;
    }

    public Date getEndDateTime() {
        return endDateTime;
    }

    public void setEndDateTime(Date endDateTime) {
        this.endDateTime = endDateTime;
    }

    public Date getDelayRealTime() {
        return delayRealTime;
    }

    public void setDelayRealTime(Date delayRealTime) {
        this.delayRealTime = delayRealTime;
    }

    public Boolean getAssign() {
        return assign;
    }

    public void setAssign(Boolean assign) {
        this.assign = assign;
    }

    public boolean isPresence() {
        return presence;
    }

    public void setPresence(boolean presence) {
        this.presence = presence;
    }

    public Date getPresenceTime() {
        return presenceTime;
    }

    public void setPresenceTime(Date presenceTime) {
        this.presenceTime = presenceTime;
    }

    public SystemUser getPresenceUser() {
        return presenceUser;
    }

    public void setPresenceUser(SystemUser presenceUser) {
        this.presenceUser = presenceUser;
    }

    public boolean isComplete() {
        return complete;
    }

    public void setComplete(boolean complete) {
        this.complete = complete;
    }

    public Date getFinishTime() {
        return finishTime;
    }

    public void setFinishTime(Date finishTime) {
        this.finishTime = finishTime;
    }

    public SystemUser getCompleteUser() {
        return completeUser;
    }

    public void setCompleteUser(SystemUser completeUser) {
        this.completeUser = completeUser;
    }

    public Set<SystemUser> getAssignUsers() {
        return assignUsers;
    }

    public void setAssignUsers(Set<SystemUser> assignUsers) {
        this.assignUsers = assignUsers;
    }

    public Set<SystemUser> getJoinUsers() {
        return joinUsers;
    }

    public void setJoinUsers(Set<SystemUser> joinUsers) {
        this.joinUsers = joinUsers;
    }

    public Set<Position> getAssignPositions() {
        return assignPositions;
    }

    public void setAssignPositions(Set<Position> assignPositions) {
        this.assignPositions = assignPositions;
    }

    public InsOrderAssignTypeEnum getOrderAssignTypeEnum() {
        return orderAssignTypeEnum;
    }

    public void setOrderAssignTypeEnum(InsOrderAssignTypeEnum orderAssignTypeEnum) {
        this.orderAssignTypeEnum = orderAssignTypeEnum;
    }

    public SystemUser getCreateUser() {
        return createUser;
    }

    public void setCreateUser(SystemUser createUser) {
        this.createUser = createUser;
    }

    public BigDecimal getLongitude() {
        return longitude;
    }

    public void setLongitude(BigDecimal longitude) {
        this.longitude = longitude;
    }

    public BigDecimal getLatitude() {
        return latitude;
    }

    public void setLatitude(BigDecimal latitude) {
        this.latitude = latitude;
    }

    public String getCompleteRemark() {
        return completeRemark;
    }

    public void setCompleteRemark(String completeRemark) {
        this.completeRemark = completeRemark;
    }

    public String getUnfinishReason() {
        return unfinishReason;
    }

    public void setUnfinishReason(String unfinishReason) {
        this.unfinishReason = unfinishReason;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    public String getCompleteFlow() {
        return completeFlow;
    }

    public void setCompleteFlow(String completeFlow) {
        this.completeFlow = completeFlow;
    }

    public Long getAuditCompleteID() {
        return auditCompleteID;
    }

    public void setAuditCompleteID(Long auditCompleteID) {
        this.auditCompleteID = auditCompleteID;
    }

    public String getDelayFlow() {
        return delayFlow;
    }

    public void setDelayFlow(String delayFlow) {
        this.delayFlow = delayFlow;
    }

    public Long getDelayFlowID() {
        return delayFlowID;
    }

    public void setDelayFlowID(Long delayFlowID) {
        this.delayFlowID = delayFlowID;
    }

    public String getCancelFlow() {
        return cancelFlow;
    }

    public void setCancelFlow(String cancelFlow) {
        this.cancelFlow = cancelFlow;
    }

    public Long getCancelFlowID() {
        return cancelFlowID;
    }

    public void setCancelFlowID(Long cancelFlowID) {
        this.cancelFlowID = cancelFlowID;
    }

    public int getLevel() {
        return level;
    }

    public void setLevel(int level) {
        this.level = level;
    }

    public boolean isAuditFirst() {
        return auditFirst;
    }

    public void setAuditFirst(boolean auditFirst) {
        this.auditFirst = auditFirst;
    }

    public boolean isAuditLast() {
        return auditLast;
    }

    public void setAuditLast(boolean auditLast) {
        this.auditLast = auditLast;
    }

    public Organization getOrganization() {
        return organization;
    }

    public void setOrganization(Organization organization) {
        this.organization = organization;
    }

    public Position getPosition() {
        return position;
    }

    public void setPosition(Position position) {
        this.position = position;
    }

    public SystemUser getAuditSystemUser() {
        return auditSystemUser;
    }

    public void setAuditSystemUser(SystemUser auditSystemUser) {
        this.auditSystemUser = auditSystemUser;
    }

    public Set<InsApplyOrder> getInsApplyOrders() {
        return insApplyOrders;
    }

    public void setInsApplyOrders(Set<InsApplyOrder> insApplyOrders) {
        this.insApplyOrders = insApplyOrders;
    }

    public InsApplyOrder getInsApplyOrder() {
        return insApplyOrder;
    }

    public void setInsApplyOrder(InsApplyOrder insApplyOrder) {
        this.insApplyOrder = insApplyOrder;
    }

    public Set<InsAuditOrder> getInsAuditOrders() {
        return insAuditOrders;
    }

    public void setInsAuditOrders(Set<InsAuditOrder> insAuditOrders) {
        this.insAuditOrders = insAuditOrders;
    }

    public String getSerial() {
        return serial;
    }

    public void setSerial(String serial) {
        this.serial = serial;
    }

    public long getTotalWorkingHours() {
        return totalWorkingHours;
    }

    public void setTotalWorkingHours(long totalWorkingHours) {
        this.totalWorkingHours = totalWorkingHours;
    }

    public long getWorkingHours() {
        return workingHours;
    }

    public void setWorkingHours(long workingHours) {
        this.workingHours = workingHours;
    }

    public String getLastRemark() {
        return lastRemark;
    }

    public void setLastRemark(String lastRemark) {
        this.lastRemark = lastRemark;
    }

    public boolean isMark() {
        return mark;
    }

    public void setMark(boolean mark) {
        this.mark = mark;
    }

    public long getExpectWorkingHours() {
        return expectWorkingHours;
    }

    public void setExpectWorkingHours(long expectWorkingHours) {
        this.expectWorkingHours = expectWorkingHours;
    }

    public boolean isCache() {
        return cache;
    }

    public void setCache(boolean cache) {
        this.cache = cache;
    }

    @Override
    public JSONObject toJSONObject() {
        JSONObject jsonObject = super.toJSONObject();
        jsonObject.put("remark",StringConverters.null2String(getLastRemark()));
        jsonObject.put("score",StringConverters.null2Int(getScore()));
        jsonObject.put("orderCode", StringConverters.null2String(getOrderCode()));
        jsonObject.put("orderName", StringConverters.null2String(getOrderName()));
        jsonObject.put("orderType", isOrderType()?"一次性":"周期性");
        jsonObject.put("startDateTime", DateTimeUtils.format(getStartDateTime(), "yyyy-MM-dd HH:mm:ss"));
        jsonObject.put("endDateTime", DateTimeUtils.format(getEndDateTime(), "yyyy-MM-dd HH:mm:ss"));
        jsonObject.put("receiveDate", DateTimeUtils.format(getReceiveDate(), "yyyy-MM-dd HH:mm:ss"));
        jsonObject.put("delayRealTime", CommonSugar.getTypedDefault(DateTimeUtils.format(getDelayRealTime(), "yyyy-MM-dd HH:mm:ss"), ""));
        jsonObject.put("delayTime", CommonSugar.getTypedDefault(DateTimeUtils.format(getDelayTime(), "yyyy-MM-dd HH:mm:ss"), ""));
        jsonObject.put("degree", StringConverters.null2String(getDegree()));
        jsonObject.put("assignType",getOrderAssignTypeEnum()!=null&&getAssign()?(orderAssignTypeEnum.getCode().equals("USER")?"指派人员":"指派岗位"):"未指派");
        jsonObject.put("createUserName",getCreateUser()==null?"":getCreateUser().getUserName());
        jsonObject.put("orderStatusEnum",getOrderStatusEnum()==null?"":getOrderStatusEnum().getCode());
        jsonObject.put("orderStatus",getOrderStatusEnum()==null?"":getOrderStatusEnum().getName());
        jsonObject.put("receiveUserName",getReceiveUser() == null ? "" : getReceiveUser().getUserName());
        jsonObject.put("presence",isPresence());
        jsonObject.put("level",StringConverters.null2Int(getLevel()));
        jsonObject.put("receive",isReceive()?"是":"否");
        jsonObject.put("finishTime", DateTimeUtils.format(getFinishTime(), "yyyy-MM-dd HH:mm:ss"));
        jsonObject.put("completeUserName",getCompleteUser() == null ? "" : getCompleteUser().getUserName());
        jsonObject.put("isDelay",getDelay());
        jsonObject.put("isCancel",getCancel());
        jsonObject.put("isCache",isCache());
        //审批类型
        String auditType="";
        if(getDelay()){
            auditType="延期审批";
        }else if(getCancel()){
            auditType="取消审批";
        }else if(getOrderStatusEnum().getCode().equals("IN_AUDITING")){
            auditType="完成审批";
        }
        jsonObject.put("auditType",auditType);
        jsonObject.put("reason",getInsApplyOrder()!=null?getInsApplyOrder().getReason():"");
        jsonObject.put("auditFirst",StringConverters.null2Boolean(auditFirst));
        jsonObject.put("auditLast",auditLast?"是":"否");
        jsonObject.put("abnormal",isAbnormal()?"异常":"正常");
        jsonObject.put("safeInstruction",StringConverters.null2Boolean(isSafeInstruction()));
        jsonObject.put("safePDF",getResource() == null ? "" : getResource().getPath());
        jsonObject.put("percent",getPercent());

        List<SystemUser> assignUsers = new ArrayList<>(getAssignUsers());
        assignUsers.sort((o1, o2) -> o1.getId() < o2.getId() ? -1 : 1);
        JSONArray usersArray = new JSONArray();
        for(SystemUser systemUser: assignUsers){
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("userName",StringConverters.null2String(systemUser.getUserName()));
            jsonObject1.put("userId",systemUser.getId());
            usersArray.add(jsonObject1);
        }

        List<Position>assignPositions = new ArrayList<>(getAssignPositions());
        assignPositions.sort((o1, o2) -> o1.getId() < o2.getId() ? -1 : 1);
        JSONArray postionsArray = new JSONArray();
        for(Position position : assignPositions){
            JSONObject jsonObject2 = new JSONObject();
            jsonObject2.put("positionName",StringConverters.null2String(position.getName()));
            jsonObject2.put("positionId",position.getId());
            postionsArray.add(jsonObject2);
        }
        jsonObject.put("totalWorkingHours",getTotalWorkingHours());
        jsonObject.put("workingHours",getWorkingHours());
        jsonObject.put("expectWorkingHours",getExpectWorkingHours());
        jsonObject.put("usersArray",usersArray);
        jsonObject.put("postionsArray",postionsArray);
        jsonObject.put("presenceTime", getPresenceTime() == null ? "" : DateTimeUtils.format(getPresenceTime(), "yyyy-MM-dd HH:mm:ss"));

/*
        jsonObject.put("presenceTime",getPresenceTime() == null ? "" :  CommonSugar.getTypedDefault(DateTimeUtils.formatDateToStringWithTime(getPresenceTime()),""));
*/
        jsonObject.put("mark",StringConverters.null2Boolean(isMark()));
        jsonObject.put("receive",isReceive()?"是":"否");
        jsonObject.put("receiveBoolean",isReceive());

        jsonObject.put("pushStatus",orderStatusEnum.getCode().equals("WAIT_PULISHING")?"待发布":"已发布");
        Set<InsApplyOrder> insApplyOrders=getInsApplyOrders();
        String cancelType="";
        String cancelReason="";
        String delayType="";
        String delayReason="";
        String delayTime="";
        String delayPerson="";
        for(InsApplyOrder x:insApplyOrders){
            if(x.getInsapplyTypeEnum().equals(InsApplyTypeEnum.CANCEL)){
                if(x.getEffective()&&((JSONArray.parseArray(getCancelFlow())!=null&&JSONArray.parseArray(getCancelFlow()).size()==x.getLevel())||getCancelFlow()==null)){

                    cancelType=x.getDictInfo().getTypeName();
                    cancelReason=x.getReason();
                }
            }else{
                if(x.getEffective()&&((JSONArray.parseArray(getDelayFlow())!=null&&JSONArray.parseArray(getDelayFlow()).size()==x.getLevel())||getDelayFlow()==null)){
                    delayType=x.getDictInfo().getTypeName();
                    delayReason=x.getReason();
                    delayTime=DateTimeUtils.formatDateToStringWithTime(x.getDelayDate());
                    delayPerson=x.getApplyUser().getUserName();
                }
            }
        }
        jsonObject.put("cancelType",cancelType);
        jsonObject.put("cancelReason",cancelReason);
        jsonObject.put("delayType",delayType);
        jsonObject.put("delayReason",delayReason);
        jsonObject.put("delayTime",delayTime);
        jsonObject.put("delayPerson",delayPerson);
        jsonObject.put("organizationName",getBelongOganization()==null?"":getBelongOganization().getOrganizationName());
        jsonObject.put("enterpriseName",getEnterprise()==null?"":getEnterprise().getEnterpriseName());

        String firstPerson="";
        String firstTime="";
        String firstOrder="";
        String firstRemark="";
        String lastPerson="";
        String lastTime="";
        String lastOrder="";
        String lastRemark="";
        Set<InsAuditOrder>auditOrders=getInsAuditOrders();
        if(CollectionUtils.isNotEmpty(auditOrders)){
            InsAuditOrder insAuditOrder= auditOrders.iterator().next();
            firstPerson=insAuditOrder.getAuditUser().getUserName();
            firstTime=DateTimeUtils.formatDateToStringWithTime(insAuditOrder.getAuditDate());
            firstOrder=insAuditOrder.getPass()?"通过":"驳回";
            firstRemark=insAuditOrder.getRemark();
            for(InsAuditOrder x:auditOrders){
                JSONArray jsonArray=JSONArray.parseArray(getCompleteFlow());
                if(jsonArray!=null&&x.getLevel()==jsonArray.size()){
                    lastPerson=x.getAuditTypeEnum().getName();
                    lastTime=DateTimeUtils.formatDateToStringWithTime(x.getAuditDate());
                    lastOrder=x.getPass()?"通过":"驳回";
                    lastRemark=x.getRemark();
                }
            }
        }
        jsonObject.put("firstPerson",firstPerson);
        jsonObject.put("firstTime",firstTime);
        jsonObject.put("firstOrder",firstOrder);
        jsonObject.put("firstRemark",firstRemark);
        jsonObject.put("lastPerson",lastPerson);
        jsonObject.put("lastTime",lastTime);
        jsonObject.put("lastOrder",lastOrder);
        jsonObject.put("lastRemark",lastRemark);

        if(getOrderStatusEnum().equals(InsOrderStatusEnum.COMPLETED)||getOrderStatusEnum().equals(InsOrderStatusEnum.IN_AUDITING)){
            jsonObject.put("result", isAbnormal() ? "异常" : "正常");//执行结果
            jsonObject.put("completeUsers", getCompleteUser()==null ? getReceiveUser().getUserName() : getCompleteUser().getUserName());//完成人
            jsonObject.put("complete", "已完成");//是否完成
        }else{
            jsonObject.put("complete", "未完成");//是否完成

        }
        return jsonObject;
    }

    public JSONObject toListJSONObject() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", getId());
        jsonObject.put("inspectionOrderName", StringConverters.null2String(getOrderName()) /*+ StringConverters.formatTime("yyyyMMdd", inspectionOrder.getCreateDate())*/);
        jsonObject.put("orderNum", StringConverters.null2String(getOrderCode()));
        jsonObject.put("startTime", StringConverters.formatTime("yy-MM-dd HH:mm:ss",getStartDateTime()));
        jsonObject.put("createDate", DateTimeUtils.format(getStartDateTime(),"MM-dd HH:mm:ss"));
        jsonObject.put("statusCode", getOrderStatusEnum().getCode());
        jsonObject.put("statusName", getOrderStatusEnum() == null ? "" : getOrderStatusEnum().getName());
        jsonObject.put("percent", getPercent());
        jsonObject.put("receiverName", getReceiveUser() == null?"":getReceiveUser().getUserName());
        return jsonObject;
    }

    public JSONObject toExportJSONObject() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", getId());
        jsonObject.put("orderName", StringConverters.null2String(getOrderName()));
        jsonObject.put("orderCode", StringConverters.null2String(getOrderCode()));
        jsonObject.put("orderType", isOrderType() ? "一次性" : "周期性");
        jsonObject.put("degree", StringConverters.null2String(getDegree()));
        jsonObject.put("orderStatus", getOrderStatusEnum() == null ? "" : getOrderStatusEnum().getName());
        jsonObject.put("createDate", StringConverters.null2String(DateTimeUtils.format(getCreateDate(), "yyyy-MM-dd HH:mm:ss")));
        jsonObject.put("startDateTime", StringConverters.null2String(DateTimeUtils.format(getStartDateTime(), "yyyy-MM-dd HH:mm:ss")));
        jsonObject.put("endDateTime", StringConverters.null2String(DateTimeUtils.format(getEndDateTime(), "yyyy-MM-dd HH:mm:ss")));
        jsonObject.put("receiveDate", StringConverters.null2String(DateTimeUtils.format(getReceiveDate(), "yyyy-MM-dd HH:mm:ss")));
        jsonObject.put("receiveUserName", getReceiveUser() == null ? "" : getReceiveUser().getUserName());
        jsonObject.put("assignType",getOrderAssignTypeEnum()!=null&&getAssign()?(orderAssignTypeEnum.getCode().equals("USER")?"指派人员":"指派岗位"):"未指派");
        //指派岗位
        List<Position> assignPositions = new ArrayList<>(getAssignPositions());
        assignPositions.sort((o1, o2) -> o1.getId() < o2.getId() ? -1 : 1);
        String assignPositionsStr = "";
        for(Position position : assignPositions){
            assignPositionsStr += StringConverters.null2String(position.getName())+ ";";
        }
        jsonObject.put("assignPositions", assignPositionsStr);
        //指派人员
        List<SystemUser> assignUsers = new ArrayList<>(getAssignUsers());
        assignUsers.sort((o1, o2) -> o1.getId() < o2.getId() ? -1 : 1);
        String assignUsersStr = "";
        for(SystemUser systemUser: assignUsers){
            assignUsersStr += StringConverters.null2String(systemUser.getUserName())+ ";";
        }
        jsonObject.put("assignUsers", assignUsersStr);
        jsonObject.put("receive",isReceive()?"是":"否");
        jsonObject.put("organizationName",getBelongOganization()==null?"":getBelongOganization().getOrganizationName());
        jsonObject.put("createUserName",getCreateUser()==null?"":getCreateUser().getUserName());
        return jsonObject;
    }
}
